export default {
	defaultBaseURL: '',
	defaultOption: {
		method: 'GET', //默认GET方式请求
		cache: 'reload', // 表示请求时忽略http缓存，但是请求完成后会刷新http缓存
		headers: {
			'Content-Type': 'application/json' //设置发送的数据类型
		},
		credentials: 'include' //请求携带cookie
	},
	/**
	 * @method get
	 * @param {String} url
	 * @param {Object} option
	 * @return {Promise} data
	 * */
	async get(url, option) {
		option = option || {};
		if (option.params) {
			url = this.initGetURL(url, option.params);
			delete option.params;
		} else {
			url = this.initGetURL(url);
		}
		let nowOption = Object.assign({}, this.defaultOption, option, {method: 'GET'});
		let response = await fetch(url, nowOption);
		let data = await response.json();
		return data;
	},
	/**
	 * @method post
	 * @param {String} url
	 * @param {Object} option
	 * @return {Promise} data
	 * */
	async post(url, option) {
		option = option || {};
		let body = '';
		if (option.data) {
			body = this.initParams(option.data);
			delete option.data;
		}
		url = this.initGetURL(url);
		let nowOption = Object.assign({},
			this.defaultOption,
			option,
			{method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'}, body});
		let response = await fetch(url, nowOption);
		let data = await response.json();
		return data;
	},
	async form(url, option) {
		option = option || {};
		let body = null;
		if (option.data) {
			body = option.data;
			delete option.data;
		}
		url = this.initGetURL(url);
		let nowOption = Object.assign({},
			this.defaultOption,
			option,
			{method: 'POST', headers: {}, body});
		let response = await fetch(url, nowOption);
		let data = await response.json();
		return data;
	},
	initParams(params) {
		let str = '';
		if (!params) {
			return str;
		}
		for (let i in params) {
			str += i + '=' + params[i] + '&';
		}
		str = str.slice(0, str.length - 1);
		return str;
	},
	initSearch(search) {
		let obj = {};
		if (!search) return obj;
		let strArr = search.slice(1).split('&');
		for (let i in strArr) {
			let item = strArr[i].split('=');
			obj[item[0]] = item[1];
		}
		return obj;
	},
	initGetURL(url, params) {
		if (!typeof url === 'string') {
			throw new Error('Expect to receive a string, but not a string')
		}
		if (url[0] !== '/') {
			url = '/' + url;
		}
		if (url.includes('?')) {
			url = url + '&' + this.initParams(params);
		} else if (params) {
			url = url + '?' + this.initParams(params);
		}
		return window.location.origin + '/' + this.defaultBaseURL + url;
	}
}